package com.kara.woodAgent.agent.codec;

import com.alibaba.fastjson2.*;
import com.alibaba.fastjson2.reader.ObjectReader;
import com.alibaba.fastjson2.reader.ObjectReaderProvider;
import com.alibaba.fastjson2.writer.ObjectWriter;
import dev.langchain4j.data.message.*;

import java.lang.reflect.Type;

/**
 * @author tzy
 * @version 1.0
 * @project wood_agent
 * @description
 * @date 2025/6/6 13:17:27
 */

public class ChatMessageMixinConfig {

	public static void configure() {

		// 注册所有消息类型的序列化器
		JSON.register(ChatMessage.class, new ChatMessageSerializer());
		JSON.register(SystemMessage.class, new ChatMessageSerializer());
		JSON.register(UserMessage.class, new ChatMessageSerializer());
		JSON.register(AiMessage.class, new ChatMessageSerializer());
		JSON.register(ToolExecutionResultMessage.class, new ChatMessageSerializer());
		JSON.register(CustomMessage.class, new ChatMessageSerializer());

		// 反序列化配置
		ObjectReaderProvider provider = JSONFactory.getDefaultObjectReaderProvider();
		provider.register(ChatMessage.class, new ChatMessageDeserializer());
		provider.register(SystemMessage.class, new ChatMessageDeserializer());
		provider.register(UserMessage.class, new ChatMessageDeserializer());
		provider.register(AiMessage.class, new ChatMessageDeserializer());
		provider.register(ToolExecutionResultMessage.class, new ChatMessageDeserializer());
		provider.register(CustomMessage.class, new ChatMessageDeserializer());
	}

	static class ChatMessageSerializer implements ObjectWriter<ChatMessage> {


		@Override
		public void write(JSONWriter jsonWriter, Object o, Object o1, Type type, long l) {

			String string = dev.langchain4j.data.message.ChatMessageSerializer.messageToJson((ChatMessage) o);
			JSONObject jsonObject = JSON.parseObject(string);
			jsonWriter.write(jsonObject);
		}
	}

	static class ChatMessageDeserializer implements ObjectReader<ChatMessage> {
		@Override
		public ChatMessage readObject(JSONReader reader, Type type, Object fieldName, long features) {
			String string = reader.readString();
			return dev.langchain4j.data.message.ChatMessageDeserializer.messageFromJson(string);

		}

	}

}
